#include <brpc/server.h>
#include <butil/logging.h>
#include <gflags/gflags.h>

#include <memory>
#include <thread>

#include "../../common/channel.h"
#include "../../common/etcd.h"
#include "../../common/log.h"
#include "main.pb.h"

DEFINE_int32(level, 1, "日志等级");
DEFINE_bool(mode, false, "调试模式-false, 发布模式-true");
DEFINE_string(path, "./logfile", "发布模式下日志输出到的文件路径");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "etcd服务器地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(instance_name, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:8080", "当前实例的外部访问地址");
DEFINE_int32(listen_port, 8080, "监听端口");

// 0. 完成Protobuf的Echo方法
class EchoServiceImpl : public example::EchoService {
   public:
    void Echo(::google::protobuf::RpcController* controller,
              const ::example::EchoRequest* request,
              ::example::EchoResponse* response,
              ::google::protobuf::Closure* done) {
        brpc::ClosureGuard closure_guard(done);

        std::string req_str = request->message();
        std::cout << "收到请求: " << req_str << std::endl;

        response->set_message(req_str);
    }
};

int main(int argc, char* argv[]) {
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    initLogger(FLAGS_level, FLAGS_mode, FLAGS_path);

    // 关闭 brpc 的日志输出
    logging::LoggingSettings log_set;
    log_set.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(log_set);

    // 1. 搭建 RPC 服务器
    brpc::Server server;

    // 2. 向服务器中，新增EchoService服务
    EchoServiceImpl echo_service;
    int ret = server.AddService(
        &echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);

    // 3. 运行 RPC 服务器
    brpc::ServerOptions options;
    options.idle_timeout_sec =
        -1;                   // 连接空闲超时时间，超时后连接关闭。-1为不会超时
    options.num_threads = 2;  // id线程数量

    ret = server.Start(FLAGS_listen_port, &options);

    if (-1 == ret) {
        std::cout << "服务启动失败" << std::endl;
        return -1;
    }

    // 4. 注册 Echo 服务
    auto registry = std::make_shared<Registry>(FLAGS_etcd_host);
    registry->registry(FLAGS_base_service + FLAGS_instance_name,
                       FLAGS_access_host);

    // 4. 休眠
    server.RunUntilAskedToQuit();

    return 0;
}